#include "sysmonitor/file_system.hpp"
#include "sysmonitor/utils.hpp"
#include <fstream>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <sys/statvfs.h> 

namespace sysmonitor {
namespace filesystem {

using namespace utils;
using namespace utils::string;

std::vector<DiskPartition> getDiskPartitions() {
    std::vector<DiskPartition> partitions;
    std::ifstream mountInfo("/proc/mounts");
    if (!mountInfo.is_open()) {
        std::cerr << "Failed to open /proc/mounts" << std::endl;
        return partitions;
    }
  
    std::string line;
    while (std::getline(mountInfo, line)) {
        std::vector<std::string> parts = split(line, ' ');
        if (parts.size() < 3) continue;
      
        // 优化: 使用更可靠的启发式方法过滤分区。
        // 通常，我们只关心以 "/dev/" 开头的物理设备或者一些网络文件系统。
        // 这里我们简单地只包含以 "/dev/" 开头的设备，这可以有效排除绝大部分虚拟文件系统。
        if (parts[0].rfind("/dev/", 0) != 0) {
            continue;
        }
      
        DiskPartition partition;
        partition.name = parts[0];
        partition.mountPoint = parts[1];
        partition.type = parts[2];
      
        // 获取磁盘使用情况
        struct statvfs stat;
        if (statvfs(partition.mountPoint.c_str(), &stat) == 0) {
            partition.totalSize = static_cast<uint64_t>(stat.f_blocks) * stat.f_frsize;
            // 使用 f_bavail (非root用户可用块数) 计算可用空间，对普通用户更有意义
            partition.freeSize = static_cast<uint64_t>(stat.f_bavail) * stat.f_frsize;
            
            if (partition.totalSize > 0) {
                partition.usedSize = partition.totalSize - partition.freeSize;
                partition.usedPercentage = static_cast<double>(partition.usedSize) / partition.totalSize * 100.0;
            }
          
            partitions.push_back(partition);
        }
    }
  
    mountInfo.close();
    return partitions;
}

DiskPartition getPartitionByMountPoint(const std::string& mountPoint) {
    auto partitions = getDiskPartitions();
    for (const auto& partition : partitions) {
        if (partition.mountPoint == mountPoint) {
            return partition;
        }
    }
  
    // 如果找不到，返回一个空的分区信息
    return DiskPartition{};
}

std::string DiskPartition::toString() const {
    std::stringstream ss;
    ss.precision(1);
    ss << name << " (" << type << ") on " << mountPoint << ": "
       << "Used=" << utils::UnitConverter::formatBytes(usedSize)
       << " / " << utils::UnitConverter::formatBytes(totalSize)
       << " (" << std::fixed << usedPercentage << "%)";
    return ss.str();
}

} // namespace filesystem
} // namespace sysmonitor
